<template>
    <div class="w750">
        <div class="submit-order" :class="themes.theme" :style="{ '--themescolor': themes.color }">
            <!-- <div class="alert--warning" style="padding: 8px 15px; font-size: 12px" v-if="getIfo.payManner == 10">
                您的订单是货到付款，商家同意退款后会联系您退还货款。
            </div> -->
            <div class="submit-list">
                <div class="submit-con" style="margin-top: 0">
                    <!-- 单个退货退款模式 -->
                    <div class="pro-mes" style="border-top: 0">
                        <div class="pro-img">
                            <legend-image
                                :pic="orderInfo.item.prodPic"
                                :type="'wh'"
                                :options="{ w: '80', h: '80' }"
                                :class="'needsclick'"
                                :isJD="orderInfo.item.prodSource == 'JD'"
                            />
                            <img src="@/assets/images/haitao-small.png" class="haitao" v-if="orderInfo.item.goodsType == 'overseas'" />
                        </div>
                        <div class="pro-name">
                            <a href="#" class="name">{{ orderInfo.item.prodName }}</a>
                            <div class="sku">{{ orderInfo.item.attribute == '' ? '' : orderInfo.item.attribute }}</div>
                            <span class="price">
                                ￥
                                <em class="now" style="color: #fd8cb0">{{ Money(orderInfo.item.prodPrice)[0] }}</em>
                                .{{ Money(orderInfo.item.prodPrice)[1] }}
                            </span>
                        </div>
                        <div class="pro-num">×{{ orderInfo.maxBasketCount }}</div>
                    </div>
                </div>

                <div class="submit-con">
                    <div class="order-style">
                        <span class="left">申请服务</span>
                        <span class="right">
                            <em class="right-em text">{{ orderInfo.serviceType == 1 ? '仅退款' : '退款退货' }}</em>
                        </span>
                    </div>
                    <div class="order-style bt">
                        <span class="left">退款原因</span>
                        <span class="right" @click="showapplyMessage">
                            <em class="right-em">{{ orderInfo.applyMessage }}</em>
                            <i class="arr"><img src="../../../assets/images/arrow.png" alt="" /></i>
                        </span>
                    </div>
                    <div class="order-style bt" v-if="orderInfo.serviceType == 2">
                        <span class="left">退货数量</span>
                        <span class="right words">
                            <input
                                class="num text-main"
                                style="text-align: left"
                                type="text"
                                :placeholder="'最多' + (orderInfo.maxBasketCount || 1) + '件'"
                                v-model.number="orderInfo.item.basketCount"
                                :disabled="!orderInfo.item.isUpdateAmount"
                            />
                            <i class="unit">件</i>
                        </span>
                    </div>
                    <div class="order-style bt">
                        <span class="left">退款金额</span>
                        <span class="right words price">
                            <input
                                class="num"
                                style="text-align: left"
                                type="text"
                                :placeholder="'最多' + (orderInfo.maxRefundAmount || 1) + '件'"
                                v-model.number="orderInfo.item.refundAmount"
                                :disabled="!orderInfo.item.isUpdateAmount"
                            />
                            <i class="unit text-main">￥</i>
                        </span>
                    </div>
                </div>
                <span style="font-size: 12px; margin-left: 10px" v-if="orderInfo.item.isUpdateAmount">
                    最多可退货数量 {{ orderInfo.maxBasketCount }} 件, 最多可退 ￥{{ orderInfo.maxRefundAmount }}
					<span v-if="orderInfo.item.freightAmount != 0">
						（含运费￥{{ orderInfo.item.freightAmount }})
					</span>
                </span>

                <div class="submit-con" v-if="orderInfo.serviceType == 2">
                    <div class="order-style" @click="showPopup">
                        <span class="left">退货方式</span>
                        <span class="right">
                            <em class="right-em text">{{ userReturnGoodsType }}</em>
                            <i class="arr"><img src="../../../assets/images/arrow.png" alt="" /></i>
                        </span>
                    </div>
                    <!-- TODO暂时没有这个需求 上门取件地址 只有当选择上门取件时才显示-->
                    <!-- <div class="order-style" style="font-weight: 700" v-if="selectReturnType == 'CALL_COLLECT'">
                        <div>
                            <van-icon name="location-o" class="rtIcon" />
                            <span>{{ orderInfo.userContactsName }}</span>
                        </div>
                        <span class="right">
                            <em class="right-em">{{ orderInfo.userContactsPhone }}</em>
                            <i class="arr" @click="goAddress"><img src="../../../assets/images/arrow.png" alt="" /></i>
                        </span>
                    </div>
                    <div class="order-style" style="margin-left: 10px" v-if="selectReturnType == 'CALL_COLLECT'">
                        {{ orderInfo.detailedAddress }}
                    </div> -->
                </div>
                <div class="submit-con">
                    <textarea class="area" placeholder="退款说明，必填" maxlength="500" v-model="orderInfo.applyRemark"></textarea>
                </div>
                <div class="submit-con">
                    <div class="file-img">
                        <span class="file-txt img">上传凭证</span>
                        <span class="add-img" v-for="(item, index) in dynamicPics" :key="index">
                            <img :src="$imgUrlHead + item" alt="" />
                            <i class="del-img" @click="delpic(dynamicPics[index], index)">×</i>
                        </span>
                        <span class="add-img files" v-show="isAddImg">
                            <em class="add-txt">+</em>
                            <!--<input type="file" name="files" class="uploader"  @change="upload" accept="image/*" ref="picture" >-->
                            <input
                                type="file"
                                name="files"
                                class="uploader hiddenInput"
                                accept="image/*"
                                @change="upload"
                                v-if="!isApp"
                                ref="picture"
                            />
                            <div @click="showpic" v-if="isApp"></div>
                        </span>
                        <p class="add-img-tip txt">温馨提示：最多添加3张图片</p>
                    </div>
                </div>
                <!-- 联系人 自行寄回时显示 -->
                <div class="submit-con" v-if="selectReturnType == 'USER_GOODS'">
                    <div class="order-style">
                        <span class="left">联系人</span>
                        <input class="num" style="text-align: left" v-model="orderInfo.userContactsName" placeholder="请输入联系人" />
                    </div>
                    <div class="order-style">
                        <span class="left">手机号码</span>
                        <input class="num text" style="text-align: left" v-model="orderInfo.userContactsPhone" placeholder="请输入手机号码" />
                    </div>
                </div>
                <div class="footerText text">提交申请后, 可能会有客服联系您, 请保持手机通畅!</div>
                <div style="height: 58px"></div>
            </div>
            <span class="apply-btn" @click="submitApply">提交申请</span>
        </div>
        <van-popup v-model="show" position="bottom">
            <van-picker :columns="columns" show-toolbar title="请选择你的退货原因" @cancel="onCancel" @confirm="onConfirm" />
        </van-popup>
        <!--上传图片选择-->
        <van-action-sheet v-model="picshow" :actions="actions" cancel-text="取消" @select="onSelect" @cancel="onCancel" />
        <!--/上传图片选择-->

        <!-- 选择退货方式 -->
        <van-popup v-model="showReturnMethod" round overlay position="bottom" title="退货方式" closeable>
            <div class="returntitle">退货方式</div>
            <van-radio-group v-model="returnSelectList">
                <van-cell-group :border="false">
                    <van-cell clickable v-for="(item, index) in orderInfo.returnGoodsTypes" :key="index">
                        <div class="title">{{ item.returnGoodsName }}</div>
                        <span style="font-size: 14px" class="text-999">{{ item.desc }}</span>
                        <template #right-icon>
                            <van-radio
                                :name="item.returnGoodsType"
                                checked-color="#FF4444"
                                @click="returnSelectListGoodsType(item.returnGoodsType, item.returnGoodsName)"
                            />
                        </template>
                    </van-cell>
                </van-cell-group>
            </van-radio-group>
            <div style="width: 90%; margin: 0 auto">
                <van-button @click="submitReturn" round block type="danger info" native-type="submit" style="margin: 64px 0 20px">确定</van-button>
            </div>
        </van-popup>
        <!-- 选择退货方式 -->
    </div>
</template>

<script>
import legendImage from 'components/legendImage/legendImage'
import { afterSale } from 'api/afterSale'
import { addressList } from 'api/addressManage'
import cash from 'utils/tool'
import { mapState } from 'vuex'
import { ActionSheet } from 'vant'
import generalServiceImpl from 'utils/upLoadPic'
import {
    refundApply,
    refundSave,
    refundReturn,
    itemRefund,
    itemReturn,
    uploadImg,
    deletePic,
    editAction,
    submitAgainApply,
    deletePhotos
} from 'api/refunds'
const MaxImg = 3
export default {
    components: {
        legendImage
    },
    data() {
        return {
            flag: false, //是否从选择地址过来
            refundAmount: '', //退款金额
            orderInfo: {
                item: {
                    prodPic: '',
                    photoFiles: []
                }
            },
            selectReturnType: '', //存储退货类型
            selectReturnName: '', //存储退货名称
            returnSelectList: '', //单选框组值
            userReturnGoodsType: '', //回显返货方式名称
            showReturnMethod: false, //显示隐藏退货方式弹出层
            photoFile: [], //照片数量
            dynamicPics: [], //存放添加图片
            Money: cash, //价格转换
            show: false,
            columns: ['未按时发货', '拍错/多拍/不喜欢', '协商一致退款', '其他'],
            actions: [
                {
                    name: '相册'
                },
                {
                    name: '相机'
                }
            ],
            picshow: false,
            isApp: false
        }
    },
    //keep alive 生命函数 每次进入页面触发
    activated() {
        // 如果flag为true 则是从选择地址返回，从localstorage获取数据
        if (this.flag) {
            let item = JSON.parse(sessionStorage.getItem('addressInfo'))
            this.orderInfo.detailedAddress = item.province + item.city + item.area + item.town + item.subAdds
            this.orderInfo.fetchProvinceId = item.provinceId
            this.orderInfo.fetchCityId = item.cityId
            this.orderInfo.fetchAreaId = item.areaId
            this.orderInfo.fetchTownId = item.townId
            this.orderInfo.userContactsName = item.receiver
            this.orderInfo.userContactsPhone = item.mobile
            this.flag = false
            return
        }

        this.getData()
    },
    //keep alive 生命函数 每次离开页面触发
    deactivated() {
        //如果为true 则证明是从选择上门地址返回
        if (this.flag) {
            return
        }
        // 销毁页面
        this.$destroy()
    },
    mounted() {
        this.Ishas()
    },
    methods: {
        //获取数据
        getData() {
            let id = this.$route.query.refundId
            this.$toast.loading({
                message: '加载中...',
                forbidClick: true
            })
            afterSale
                .getUpdateApply({
                    refundId: id
                })
                .then((res) => {
                    if (res.status == 1) {
                        this.orderInfo = res.result
                        let list = res.result.returnGoodsTypes.find((item) => item.isSelected) //是否有默认选中的返货方式
                        if (list) {
                            this.userReturnGoodsType = list.returnGoodsName //查找默认选中的返货名称
                            this.returnSelectList = list.returnGoodsType //查找默认选中的返货类型
                        }
                        if (res.result.photoFiles) {
                            this.dynamicPics = res.result.photoFiles
                        } else {
                            this.dynamicPics = []
                        }
                    } else {
                        this.$toast(res.msg)
                    }
                })
                .finally(() => {
                    this.$toast.clear()
                })
        },

        //去修改地址
        goAddress() {
            this.flag = true
            // 传递flag 标记从售后详情过去
            this.$router.push({
                path: '/addressList',
                query: {
                    type: 'after'
                }
            })
        },
        //选择返货方式
        returnSelectListGoodsType(type, name) {
            //存储起来
            this.returnSelectList = type
            this.selectReturnName = name
        },
        //退货方式确定按钮
        submitReturn() {
            if (this.returnSelectList == 'CALL_COLLECT') {
                this.$toast('暂不支持此服务')
                return
            }
            this.selectReturnType = this.returnSelectList
            this.userReturnGoodsType = this.selectReturnName
            this.showReturnMethod = false
        },
        //显示退货方式弹出层
        showPopup() {
            this.showReturnMethod = true
        },
        //是否是app
        Ishas() {
            if (window.plus) {
                this.isApp = true
            } else {
                this.isApp = false
            }
        },
        // 弹出上传
        showpic() {
            this.picshow = true
        },
        //关闭弹窗
        onCancel() {
            this.picshow = false
        },
        onSelect(item) {
            this.picshow = false
            if (item.name == '相册') {
                this.appendByGallery()
            } else if (item.name == '相机') {
                this.getImage()
            }
        },
        //相册上传图片
        appendByGallery() {
            let This = this
            generalServiceImpl.appendByGallery().then((res) => {
                This.dynamicPics.push(res)
                let index = this.dynamicPics.length - 1
                This.photoFile[' + index + '] = res
            })
        },
        //拍照上传图片
        getImage() {
            let This = this
            generalServiceImpl.getImage().then((res) => {
                This.dynamicPics.push(res)
                let index = this.dynamicPics.length - 1
                This.photoFile[' + index + '] = res
            })
        },
        goback() {
            this.$router.back()
            this.$router.isBack = true
        },
        //提交申请
        submitApply() {
            let params = {}
            let regRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g
			//当退货退款时
			if (this.orderInfo.item.basketCount === '' || this.orderInfo.item.basketCount > this.orderInfo.maxBasketCount) {
				this.$toast('亲,请填写正确的退货数量，且不能大于' + (this.orderInfo.maxBasketCount || 1) + '件')
				return
			}

            if (this.orderInfo.item.refundAmount === '' || this.orderInfo.item.refundAmount > this.orderInfo.maxRefundAmount) {
                this.$toast('亲,请填写正确的退款金额，且不能大于' + this.orderInfo.maxRefundAmount + '元')
                return
            }
            //没有选择退款原因
            if (this.orderInfo.applyMessage == '') {
                this.$toast('亲,请选择退款原因')
                return
            }
            //退款说明不符合
            if (this.orderInfo.applyRemark && this.orderInfo.applyRemark.match(regRule)) {
                this.$toast('退款说明不支持表情')
                return
            }
			if (!this.orderInfo.applyRemark || this.orderInfo.applyRemark.trim() == '') {
                this.$toast('退款说明不能为空')
                return
            }
            //当退款退货时 添加返货方式
            if (this.orderInfo.serviceType == 2) {
                if (this.returnSelectList == '') {
                    this.$toast('亲,请选择返货方式')
                    return
                }
                params.userReturnGoodsType = this.returnSelectList
            }
            //当有照片时
            if (this.dynamicPics.length > 0 && this.dynamicPics[0] !== []) {
                params.photoFiles = this.dynamicPics.join()
            }
            //给表单赋值
            params.refundAmount = this.orderInfo.item.refundAmount //金额
            params.basketCount = this.orderInfo.item.basketCount //数量
            params.refundId = this.orderInfo.refundId //售后id
            params.applyMessage = this.orderInfo.applyMessage //申请原因
            params.userContactsName = this.orderInfo.userContactsName //用户联系人
            params.userContactsPhone = this.orderInfo.userContactsPhone //用户联系人手机号
            params.applyRemark = this.orderInfo.applyRemark //售后说明
            params.fetchAreaId = this.orderInfo.fetchAreaId
            params.fetchCityId = this.orderInfo.fetchCityId
            params.fetchProvinceId = this.orderInfo.fetchProvinceId
            params.fetchDetailedAddress = this.orderInfo.fetchDetailedAddress

            //提交行为
            this.$toast.loading({
                forbidClick: true,
                message: '申请提交中'
            })
            setTimeout(() => {
                afterSale.updateApplySubmit(params).then((res) => {
                    if (res.status == 1) {
                        this.getMsg()
                    } else {
                        this.$toast({ message: res.msg })
                    }
                })
            }, 1000)
        },
        getMsg() {
            this.$toast({
                forbidClick: true,
                message: '提交成功'
            })
            setTimeout(() => {
                this.gobackPach()
            }, 1500)
        },
        //是否为正整数
        isPositiveNum(s) {
            let re = /^[0-9]*[1-9][0-9]*$/
            return re.test(s)
        },
        showapplyMessage() {
            this.show = true
        },
        onConfirm(e) {
            this.orderInfo.applyMessage = e
            this.show = false
        },
        onCancel() {
            this.show = false
        },
        upload(e) {
            let _this = this
            var files = e.target.files[0]
            if (files) {
                if (!e || !window.FileReader) return // 看支持不支持FileReader
                let reader = new FileReader()
                reader.onloadend = function () {
                    // _this.portraitPic = this.result
                }
                let file = e.target.files[0]
                var data = new FormData()
                data.append('photos', this.$refs.picture.files[0])

                this.$toast.loading({
                    message: '上传中',
                    forbidClick: true,
                    duration: 0
                })

                uploadImg(data).then((res) => {
                    if (res.status == 1) {
                        this.$toast.clear()
                        this.$toast('上传成功')
                        this.dynamicPics.push(res.result[0])
                        let index = this.dynamicPics.length - 1
                        this.photoFile[' + index + '] = res.result
                    } else {
                        this.$toast('上传失败')
                    }
                })
            }
        },
        //删除图片
        delpic(picPath, index) {
            let ImgIndex = index
            let imgs = this.dynamicPics
            this.$dialog
                .confirm({
                    title: '是否删除此张图片',
                    message: '请再三考虑哦~~~'
                })
                .then(() => {
                    deletePhotos({ photos: imgs[ImgIndex] }).then((res) => {
                        if (res.status == 1) {
                            this.$toast('删除成功')
                            imgs.splice(ImgIndex, 1)
                            this.dynamicPics = imgs
                        } else {
                            this.$toast(res.msg)
                        }
                    })
                })
                .catch(() => {
                    // on cancel
                })
        },
        gobackPach() {
            this.$router.replace({
                path: `/returnList`
            })
        }
    },
    computed: {
        ...mapState(['themes']),
        isAddImg() {
            if (this.dynamicPics.length >= MaxImg) {
                return false
            } else {
                return true
            }
        }
    }
}
</script>

<style src="../../../assets/css/return.css" scoped></style>
<style src="../../../assets/css/popup.css" scoped></style>
<style src="../../../assets/css/submit-order.css" scoped></style>
<style src="../../../assets/css/style/submit-order-style.css" scoped></style>
<style scoped>
.files {
    position: relative;
}
.files input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    /*width: 100%;*/
    height: 100%;
}
.files div {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    width: 100%;
    height: 100%;
}
.submit-order .submit-list .submit-con .right.words .num {
    background: transparent;
}

.returntitle {
    text-align: center;
    padding: 20px;
    font-style: 14px;
}
.title {
    font-size: 16px;
}
.returnText {
    margin: 5px 3px;
    padding: 0 3px;
    background-color: #fee6e8;
    font-size: 12px !important;
    color: #f24e79;
}
.text {
    color: #969799 !important;
}
.img {
    margin-right: 10px;
}
.txt {
    margin-left: 57px;
}
.priceInfo {
    display: flex;
    justify-content: space-between;
}
.rtIcon {
    vertical-align: middle;
    padding: 0 0.08rem 0.08rem 0;
}
.footerText {
    padding: 10px;
    text-align: left;
    font-size: 14px;
}
</style>
